#include "btndelegate.h"

#include <QApplication>
#include <QMouseEvent>
#include <QMessageBox>
#include <QPainter>
#include <QStyleOption>
// #include <QDesktopWidget>
#include <QToolTip>
#include <QDebug>
#include <iostream>

TableViewBtnDelegate::TableViewBtnDelegate(QStringList btnNames, QWidget *parent)
    : QStyledItemDelegate(parent),
      m_btnNames(btnNames)
{

    for (int i = 0; i < btnNames.size(); ++i)
    {
        m_btns.push_back(QSharedPointer<QPushButton>(new QPushButton()));
        m_btns[i]->setStyleSheet("QPushButton{border-width: 0px;\
                           position: absolute;\
                           left: 0px;\
                           top: 0px;\
                           width:120px;\
                           height: 30px;\
                           background: inherit;\
                           background-color: rgba(255, 255, 255, 0);\
                           border-width: 1px;\
                           border-style: solid;\
                           border-color: rgba(2, 182, 212, 1);\
                           border-radius: 10px;\
                           font-size: 11px;\
                           color: #000000;}\
                           QPushButton:hover{background-color:rgba(2, 182, 212, 1); color:#FFFFFF;}");
    }
}

TableViewBtnDelegate::~TableViewBtnDelegate()
{

}

// 绘制按钮
void TableViewBtnDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem viewOption(option);
    initStyleOption(&viewOption, index);
    if (option.state.testFlag(QStyle::State_HasFocus))
        viewOption.state = viewOption.state ^ QStyle::State_HasFocus;

    painter->save();
    QStyledItemDelegate::paint(painter, viewOption, index);

    // 计算按钮显示区域
    int nCount = m_btnNames.count();
    if(nCount == 0)
    {
        return;
    }

    // 计算每个按钮所需的最小宽度
    QVector<int> buttonWidths(nCount);
    QFontMetrics fm(painter->font());
    int totalWidth = 0;
    const int margin = 10;//按钮边距
    for(int i = 0; i < nCount; ++i)
    {
        int textWidth = fm.width(m_btnNames.at(i));
        buttonWidths[i] = textWidth + 2 * margin;
        totalWidth += buttonWidths[i];
    }

    //计算可以用宽度
    int availableWidth = option.rect.width();

    // 如果总宽度小于可用宽度，将多余的宽度平均分配给每个按钮
    if (totalWidth < availableWidth) {
        int extraWidth = availableWidth - totalWidth;
        int extraPerButton = extraWidth / nCount;
        for (int i = 0; i < nCount; ++i) {
            buttonWidths[i] += extraPerButton;
        }
    }

    // 绘制按钮
    int currentX = option.rect.x();
    for (int i = 0; i < nCount; ++i)
    {
        QStyleOptionButton button;
        //button.rect =  option.rect.adjusted(4 + i*w , 4, -(w * ( nCount - i -1 ) + 4)  , -4);
        button.rect = QRect(currentX + 4, option.rect.y() + 4, buttonWidths[i] - 8, option.rect.height() - 8);
        button.text = m_btnNames.at(i);
        button.state |= QStyle::State_Enabled;

        if (button.rect.contains(m_mousePoint))
        {
            if (m_nType == 0)
            {
                button.state |= QStyle::State_MouseOver;
            }
            else if (m_nType == 1)
            {
                button.state |= QStyle::State_Sunken;
            }
        }

        auto& btnPtr = m_btns[i];
        btnPtr.data()->style()->drawControl(QStyle::CE_PushButton, &button, painter, btnPtr.data());
        currentX += buttonWidths[i];
    }
    painter->restore();
}

// 响应按钮事件 - 划过、按下
bool TableViewBtnDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index)
{
    m_nType = -1;
    bool bRepaint = false;
    QMouseEvent *pEvent = static_cast<QMouseEvent *> (event);
    m_mousePoint = pEvent->pos();

    int nCount = m_btnNames.count();

    int w = nCount != 0 ? option.rect.width() / nCount : 0;
    if(w < 0) {
        return false;
    }

    // 还原鼠标样式
    QApplication::restoreOverrideCursor();

    for (int i = 0; i < nCount; ++i)
    {
        QStyleOptionButton button;
        button.rect =  option.rect.adjusted(4 + i*w , 4, -(w * ( nCount - i -1 ) + 4)  , -4);

        // 鼠标位于按钮之上
        if (!button.rect.contains(m_mousePoint))
            continue;

        bRepaint = true;
        switch (event->type())
        {
        // 鼠标滑过
        case QEvent::MouseMove:
        {
            // 设置鼠标样式为手型
            QApplication::setOverrideCursor(Qt::PointingHandCursor);

            m_nType = 0;

            QToolTip::showText(pEvent->globalPos(), m_btnNames.at(i));
            break;
        }
        // 鼠标按下
        case QEvent::MouseButtonPress:
        {
            m_nType = 1;
            break;
        }
        // 鼠标释放
        case QEvent::MouseButtonRelease:
        {
            emit oper(index, m_btnNames.at(i));
            break;
        }
        default:
            break;
        }
    }

    return bRepaint;
}

